package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.LanguageData;
import com.example.demo.mapper.LanguageDataMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/***
 ** Create by Wedream on 2021/7/16
 */
@RestController
@RequestMapping("/languageData")
public class LanguageDataController {

    @Resource
    LanguageDataMapper languageDataMapper;

    @PostMapping  //增
    public Result<?> save(@RequestBody LanguageData languageData) {
        languageDataMapper.insert(languageData);
        return Result.success();
    }

    @DeleteMapping("/{id}") //删
    public Result<?> delete(@PathVariable long id) {
        languageDataMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping //查
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "2020") Integer pageSize,
                              @RequestParam(defaultValue = "",required = false) String search) {

        LambdaQueryWrapper<LanguageData> wrapper = Wrappers.<LanguageData>lambdaQuery();
        if(StrUtil.isNotBlank(search)) {
           wrapper.like(LanguageData::getDate,search);
        }
        Page<LanguageData> languageDataPage = languageDataMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        // 不同年份来一个使用率
        List<LanguageData> records = languageDataPage.getRecords();
        Map<String,Boolean> mp = new HashMap<>();
        List<LanguageData> res = new ArrayList<>();

        for (LanguageData languageData : records) {
            String str = languageData.getLanguage() + languageData.getDate().substring(0, 4); //生成唯一键
            if (!mp.containsKey(str)) {
                res.add(new LanguageData(languageData.getId(), languageData.getLanguage(),
                        languageData.getDate().substring(0, 4), languageData.getPercent()));
                mp.put(str, true);
            }
        }

        Collections.sort(res);
        languageDataPage.setRecords(res);

        return Result.success(languageDataPage);
    }


    @PutMapping //改
    public Result<?> update(@RequestBody LanguageData languageData) {
        languageDataMapper.updateById(languageData);
        return Result.success();
    }
}
